//app.js
const Towxml = require('/towxml/main');
const Base64 = require('./utils/base64.js');

const AV = require('/libs/leancloud/av-weapp-min.js');
// LeanCloud 应用的 ID 和 Key
AV.init({
    appId: 'Jgus2Hph0qMnuAp9L7kKOikb-MdYXbMMI',
    appKey: 'V0nX8eDdjGbFCE6yAM0xNMnv',
});

// 本地缓存键值对说明
// user_info: 用户信息
// config: 小白AI控制数据
App({
    onLaunch: function() {
        let that = this;
        const updateManager = wx.getUpdateManager()
        updateManager.onCheckForUpdate(function (res) {
            // 请求完新版本信息的回调
            if (res.hasUpdate) {
                updateManager.onUpdateReady(function () {
                    wx.showModal({
                        title: '更新提示',
                        content: '新版本已经准备好，点击确定重启！',
                        showCancel: false,
                        success: function (res) {
                            if (res.confirm) {
                                // 新的版本已经下载好，调用 applyUpdate 应用新版本并重启
                                updateManager.applyUpdate()
                            }
                        }
                    })
                })
            }
        })
        let config = wx.getStorageSync('config') || null;
        // 拉取远程配置
        that.fetchGlobalConfig();

        // 登录
        wx.login({
            success: res => {
                // 发送 res.code 到后台换取 openId, sessionKey, unionId
            }
        })
        // leancloud 登陆
        AV.User.loginWithWeapp().then(user => {
            console.log('leancloud 登陆成功')
            // user.authData.lc_weapp
            that.globalData.leancloud_user = user;
            // user.attributes.authData.lc_weapp.openid
            // user.attributes.authData.lc_weapp.session_key
        }).catch(console.error);
        
        // 获取用户信息
        wx.getSetting({
            success: res => {
                if (res.authSetting['scope.userInfo']) {
                    // 已经授权，可以直接调用 getUserInfo 获取头像昵称，不会弹框
                    wx.getUserInfo({
                        success: ({ userInfo }) => {
                            console.log(userInfo);
                            // 可以将 res 发送给后台解码出 unionId
                            this.globalData.userInfo = userInfo

                            // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
                            AV.User.loginWithWeapp().then(user => {
                                // 更新当前用户的信息
                                user.set(userInfo).save().then(user => {
                                    // 成功，此时可在控制台中看到更新后的用户信息
                                }).catch(console.error);
                            }).catch(console.error);
                            // 所以此处加入 callback 以防止这种情况
                            if (this.userInfoReadyCallback) {
                                this.userInfoReadyCallback(res)
                            }
                        }
                    })
                } else {
                    console.log('用户未授权')
                }
            }
        })
    },
    onShow: function() {

    },
    fetchGlobalConfig: function(call_back) {
        let that = this;

        // wx.showLoading({
        //     title: '加载中...',
        // })
        // setTimeout(function () {
        //     wx.hideLoading()
        // }, 8000)
        wx.request({
            url: that.globalData.gitee.target_url + '/' + that.globalData.gitee.global_config_filename,
            data: {
                access_token: that.globalData.gitee.access_token,
                ref: that.globalData.gitee.branch
            },
            success: function (res) {
                let output = that.base64.decode(res.data.content);
                that.globalData.config = JSON.parse(output);
                console.log('请求全局配置数据成功:',that.globalData.config);
                //wx.hideLoading();
                //console.log(that.globalData.config)
                call_back(true, that.globalData.config);
            },
            fail: function (e) {
                console.log('请求全局配置数据失败');
                //wx.hideLoading();
                call_back(false, null);
            }
        })
    },
    towxml: new Towxml(),
    base64: new Base64(),
    globalData: {
        leancloud_user: null,
        userInfo: null,
        systenInfo: null,
        gitee: {
            "openapi": "https://gitee.com/api/v5/swagger",
            "api_base": "https://gitee.com/api",
            "owner": "hsxsb",
            "repository": "blog_xsb",
            "branch": "master",
            "target_url": "https://gitee.com/api/v5/repos/hsxsb/blog_xsb/contents/hexoapp/source/_data/target",
            "posts_url": "https://gitee.com/api/v5/repos/hsxsb/blog_xsb/contents/hexoapp/source/_posts",
            "gank_output_url": "https://gitee.com/api/v5/repos/hsxsb/blog_xsb/contents/hexoapp/source/_data/gank",
            "gank_url": "https://gitee.com/api/v6/repos/hsxsb/blog_xsb/contents/hexoapp/source/_gank",
            "global_config_filename": "global_config.json",
            "access_token": "a9c878d429b09bdcd017ba91d16b4223"
        },
        config: null,
        poster_cropper_url: null
    },
    deleteArraySpecifyKey: function(arr, key, del) {
        for (let i = 0; i < arr.length; i++) {
            //console.log(arr[i].key + ', ' + key)
            if (arr[i].key === key) {
                if (del) {
                    arr.splice(i, 1)
                }
                return true;
            }
        }

        return true;
    },
    getLeanCloudACL: function (read, write) {
        let acl = new AV.ACL();
        acl.setPublicReadAccess(read);
        acl.setPublicWriteAccess(write);
        return acl;
    },
    writeUserOpenid: function (userid, openid, session_key, is_subscribed, type) {
        let that = this;
        // 未存在会创建新表
        let Users = AV.Object.extend('Users');
        let newUsers = new Users();
        newUsers.setACL(that.getLeanCloudACL(true, true));
        newUsers.set('userid', userid);
        newUsers.set('openid', openid);
        newUsers.set('session_key', session_key);
        newUsers.set('is_subscribed', is_subscribed);
        newUsers.set('s_type', type)
        newUsers.save().then(ret => {
            // nothing to do
            console.log('初始化用户表成功');
        }).catch(ex => {
            console.log(ex)
            wx.showToast({
                title: '创建用户表失败',
                icon: 'none',
                duration: 2000
            });
        });
    },
    updateUserSubscribe: function (userid, openid, session_key, is_subscribed, type) {
        let that = this;
        let query = new AV.Query('Users');
        query.equalTo('userid', userid);
        query.find().then(ret => {
            //console.log(ret);
            if (ret.length > 0) {
                let v = ret[0];
                v.set('userid', userid);
                v.set('openid', openid);
                v.set('session_key', session_key);
                v.set('is_subscribed', is_subscribed);
                v.set('s_type', type);
                v.save().then(rt => {
                    // 页面计数更新成功
                    console.log('用户信息更新成功');
                }).catch(ex => {
                    console.log(ex)
                    // 页面计数更新失败
                    console.log('用户信息更新失败');
                });
            } else {
                // 小程序端先于PC端访问，则需要创建该条记录
                let Users = AV.Object.extend('Users');
                let users = new Users();

                users.setACL(that.getLeanCloudACL(true, true));
                users.set('userid', userid);
                users.set('openid', openid);
                users.set('session_key', session_key);
                users.set('is_subscribed', is_subscribed);
                users.set('s_type', type);

                users.save();
            }
        }).catch(ex => {
            console.log(ex.message);
            console.log(ex.code);
            if (ex.code == 101) {
                console.log('用户表未存在，开始创建');
                that.writeUserOpenid(userid, openid, session_key, is_subscribed, type);
            }
        });
    },
})
